package com.atguigu.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.cart.feign.ProductFeignService;
import com.atguigu.cart.interceptor.CartInterceptor;
import com.atguigu.cart.service.ICartService;
import com.atguigu.cart.vo.CartItemVO;
import com.atguigu.cart.vo.CartVO;
import com.atguigu.cart.vo.UserInfoDTO;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.to.SkuInfoVO;
import com.atguigu.common.tool.utils.Func;
import com.atguigu.common.utils.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author : wenchao.long
 * @date : Created in 2021/8/16 14:48 周一
 * @description :
 */
@Slf4j
@Service
@AllArgsConstructor
public class CartServiceImpl implements ICartService {

    private final StringRedisTemplate redisTemplate;

    private final ProductFeignService productFeignService;

    private final ThreadPoolExecutor executor;

    @Override
    public CartItemVO addToCart(Long skuId, Integer num) {

        BoundHashOperations<String, Object, Object> operations = getCartOps();
        String res = (String) operations.get(String.valueOf(skuId));

        if (Func.isNotEmpty(res)) {
            // 如果不是null 证明是添加商品
            CartItemVO cartItem = JSON.parseObject(res, CartItemVO.class);
            cartItem.setCount(cartItem.getCount() + num);
            operations.put(String.valueOf(skuId), JSON.toJSONString(cartItem));
            return cartItem;
        }

        CartItemVO cartItem = new CartItemVO();

        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            // 1. 远程查询当前要添加的商品的信息
            R info = productFeignService.info(skuId);
            SkuInfoVO skuInfo = info.getData(new TypeReference<SkuInfoVO>() {
            });

            cartItem.setCheck(true)
                    .setCount(num)
                    .setImage(skuInfo.getSkuDefaultImg())
                    .setTitle(skuInfo.getSkuTitle())
                    .setSkuId(skuId)
                    .setPrice(skuInfo.getPrice());
        }, executor);

        // 远程查询sku的组合信息
        CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
            List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
            cartItem.setSkuAttr(skuSaleAttrValues);
        }, executor);

        try {
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValuesTask).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        operations.put(String.valueOf(skuId), JSON.toJSONString(cartItem));

        return null;
    }

    @Override
    public CartItemVO getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(String.valueOf(skuId));
        return JSON.parseObject(o, CartItemVO.class);
    }

    @Override
    public CartVO getCart() {
        CartVO cartVO = new CartVO();
        UserInfoDTO userInfo = CartInterceptor.threadLocal.get();
        Long userId = userInfo.getUserId();
        String userKey = userInfo.getUserKey();

        if (userId != null) {

            // 1. 登录状态
            String cartKey = CartConstant.CART_PREFIX + userId;

            String tempKey = CartConstant.CART_PREFIX + userKey;

            // 2. 如果临时购物车的数据还没有进行合并
            List<CartItemVO> tempCartItems = getCartItems(tempKey);
            if (Func.isNotEmpty(tempCartItems)) {
                for (CartItemVO cartItem : tempCartItems) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                // 清除临时购物车的数据
                clearCart(tempKey);
            }

            // 3. 获取登录后的购物车的数据 [包含合并过来的临时购物车的数据 和登录后的购物车的数据]
            List<CartItemVO> cartItems = getCartItems(cartKey);
            cartVO.setItems(cartItems);

        } else {
            // 2. 没登录
            String cartKey = CartConstant.CART_PREFIX + userKey;
            cartVO.setItems(getCartItems(cartKey));
        }
        return cartVO;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVO cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        cartOps.put(String.valueOf(skuId), JSON.toJSONString(cartItem));
    }

    @Override
    public void changItemCount(Long skuId, Integer num) {
        CartItemVO cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(String.valueOf(skuId), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(String.valueOf(skuId));
    }

    @Override
    public List<CartItemVO> getUserCartItems() {
        UserInfoDTO user = CartInterceptor.threadLocal.get();
        Long userId = user.getUserId();
        if (userId == null) {
            return null;
        }
        String cartKey = CartConstant.CART_PREFIX + userId;
        return Objects.requireNonNull(getCartItems(cartKey))
                .stream()
                .filter(CartItemVO::getCheck)
                .peek(item -> {
                    R r = productFeignService.getPrice(item.getSkuId());
                    item.setPrice(r.getData(new TypeReference<BigDecimal>() {
                    }));
                })
                .collect(Collectors.toList());

    }

    /**
     * 获取 我们要操作的购物车
     *
     * @return bound
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoDTO userInfo = CartInterceptor.threadLocal.get();
        Long userId = userInfo.getUserId();
        String userKey = userInfo.getUserKey();

        String cartKey;
        if (userId != null) {
            cartKey = CartConstant.CART_PREFIX + userId;
        } else {
            cartKey = CartConstant.CART_PREFIX + userKey;
        }

        return redisTemplate.boundHashOps(cartKey);
    }

    private List<CartItemVO> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (Func.isNotEmpty(values)) {
            return values.stream()
                    .map(value -> JSON.parseObject(Objects.toString(value), CartItemVO.class))
                    .collect(Collectors.toList());
        }
        return null;
    }

}
